package com.tiantianyuegou.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.UserInfoModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.SelfUtils;
import com.tiantianyuegou.util.StringUtils;
import com.tiantianyuegou.util.ToastUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 登陆界面
 */
public class LoginActivity extends BaseActivity  implements View.OnClickListener,TextWatcher {

//    http://hjtech.wicp.net:8080/tiantianyuegou-api/member/login?account=15036035654&password=123456 登陆接口
    private EditText edt_login_number, edt_login_pwd;
    private TextView tx_forget_pwd, tx_register_account;
    private Button btn_login;
    LoadingDialog loadingDialog;
    private String TAG = "LoginActivity";
    private String mType;
    private String phone;
    private String password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Tools.changeSystemBar(this);
        setTitle(R.string.login_title);
        initViews();
    }



    /**
     * 查找控件
     */
    @Override
    public void findViewByIds() {
        edt_login_number = (EditText) findViewById(R.id.edt_login_number);
        edt_login_pwd = (EditText) findViewById(R.id.edt_login_pwd);
        tx_register_account = (TextView) findViewById(R.id.tx_register_account);
        tx_forget_pwd = (TextView) findViewById(R.id.tx_forget_pwd);
        btn_login = (Button) findViewById(R.id.btn_login);

    }

    /**
     * 设置监听事件
     */
    @Override
    public void initListener() {
        loadingDialog = new LoadingDialog(this);
        tx_register_account.setOnClickListener(this);
        tx_forget_pwd.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        edt_login_number.addTextChangedListener(this);
        edt_login_pwd.addTextChangedListener(this);

    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        mType=getIntent().getStringExtra("type");
    }

    /**
     * 登陆
     */
    public void login() {

        String mobile = edt_login_number.getText().toString().trim();
        String pwd = edt_login_pwd.getText().toString().trim();
        SPHelper.setPassword(pwd);

        if (TextUtils.isEmpty(mobile)) {
            showMsg("请输入手机号码");
            return;
        }
        if (!StringUtils.checkPhone(mobile)) {
            showMsg("手机号码格式错误");
            return;
        }
        if (SelfUtils.isConSpeCharacters(pwd)) {
            showMsg("密码中不能包含特殊字符");
            return;
        }
        if (pwd.length() < 6 || pwd.length() > 20) {
            showMsg("请输入6-20位长度的密码");
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            showMsg("请输入密码");
            return;
        }
        loadingDialog.showDialog();
        loadingDialog.setMsg("登录中");
        RequestParams params = new RequestParams();
        params.addBodyParameter("account", mobile);
        params.addBodyParameter("password", pwd);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.LOGIN, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取失败");
                    return;
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONObject object = jsonObject.getJSONObject("member");
                            String tmId = object.getString("tmId");
                            String tmPhone = object.getString("tmMobile");
                          /*  if (!jsonObject.toString().contains("tmAvatar\":null")) {
                                String tmAvater = jsonObject.getString("tmAvatar");
                            }*/
                            String tmName = object.getString("tmName");
                            SPHelper.setTmId(tmId);
                            SPHelper.setTmPhone(edt_login_number.getText().toString().trim());
                            SPHelper.setPassword(edt_login_pwd.getText().toString().trim());
                            if (mType.equals("GoodsDetailActivity") || mType.equals("CategoryFragment") || mType.equals("mine")) {
                                finish();
                            } else {
                                Intent login = new Intent();
                                login.setClass(LoginActivity.this, MainActivity.class);
                                startActivity(login);
                                finish();
                            }
                            loadMember();
                        } else if (code.equalsIgnoreCase("101")) {
                            showMsg("登陆失败");
                        } else if (code.equalsIgnoreCase("103")) {
                            showMsg("账号尚未注册");
                            loadingDialog.dismiss();
                        } else if (code.equalsIgnoreCase("104")) {
                            showMsg("密码错误");
                            loadingDialog.dismiss();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("登录失败");
                        loadingDialog.dismiss();
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查网络设置");
            }
        });
    }
    private void loadMember() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tm_id", SPHelper.getTmId());
        Log.e("Main", "Main loadMember" + SPHelper.getTmId());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.USER_INFO, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Log.e("MemberFragment", "onSuccess response.result  "
                        + responseInfo.result);
                String returnstr = responseInfo.result;

                try {
                    JSONObject json = new JSONObject(returnstr);
                    String code = json.getString("code");
                    Log.e("MemberFragment", json.getString("message"));

                    if (code.equals("100")) {
                        JSONObject jsonObject = json.getJSONObject("member");

//                        new UserInfoModel().setTmAvatar(jsonObject.getString("tmAvatar"));

                        SPHelper.setTmGuanCount(jsonObject.getString("tmGuanCount"));
                        SPHelper.setTmRedCount(jsonObject.getString("tmRedCount"));
                        Log.e("tag", "获取一些会员的数据");
                        // jsonObject.getString("");
                    } else {
                        Log.e("MemberFragment", "else code ！= 100");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("MemberFragment", "MemberFragment try catch" + e.toString());
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", "error" + s);
                Log.e("MemberFragment", "MemberFragment onFailure");

            }
        });
    }

            @Override
    public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.tx_register_account:
                        Intent register = new Intent();
                        register.setClass(LoginActivity.this, RegisterActivity.class);
                        startActivity(register);
                        break;
                    case R.id.tx_forget_pwd:
                        Intent forgetPwd = new Intent();
                        if (getIntent().hasExtra("type")) {
                            forgetPwd.putExtra("type",mType);
                        }
                        forgetPwd.setClass(LoginActivity.this, ForgetPwdActivity.class);
                        startActivityForResult(forgetPwd, Constant.FORGETPWD_REQUEST1);
                        break;
                    case R.id.btn_login:
                        login();
                        break;
                    default:
                        break;
                }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==Constant.FORGETPWD_REQUEST1){
            if(resultCode==Constant.FORGETPWD_RESULT){
                mType=data.getStringExtra("type");
            }
        }
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String mobile = edt_login_number.getText().toString().trim();
        String pwd = edt_login_pwd.getText().toString().trim();
        if (mobile != null && pwd != null && !"".equals(mobile) && !"".equals(pwd)) {
            btn_login.setEnabled(true);
            btn_login.setAlpha(1.0f);
        } else {
            btn_login.setEnabled(false);
            btn_login.setAlpha(0.5f);
        }
    }


}
